var indexs; //基本情况收集单
var _privateSingle; //收集单id
var _privateSingles; //收集单详情id
var subject = {}; //题库
var upload_img_URL = {}; //用户问诊上传图片
var suject_Radiosanser = {}; //收集单选
var suject_Checkboxsanser = {}; //收集多选
var suject_textareas = {}; //简答题

//function createonclick(roomid) {
$(".layim-chat-main").on("click", function() {
	$(".medication_S").css("display", "none");
	$(".all_Collect").css("display", "none");
});

$(".close_been").on("click", () => {
	$(".all_Collect").css("display", "none");
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
})
var show_button_one = () => {
	$('.Invite_a_doctor_show').css({
		'display': 'block'
	})
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
	$('.information_to').css({
		'display': 'none'
	})
	$('.all_Collect').css({
		'display': 'none'
	})
	$('.medication_S').css({
		'display': 'none'
	})
};

var show_button_two = () => {
	$('.Invite_a_doctor_show').css({
		'display': 'none'
	})
	$('.assign_a_doctor_show').css({
		'display': 'block'
	})
	$('.information_to').css({
		'display': 'none'
	})
	$('.all_Collect').css({
		'display': 'none'
	})
	$('.medication_S').css({
		'display': 'none'
	})
}

var show_button_three = () => {
	$('.Invite_a_doctor_show').css({
		'display': 'none'
	})
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
	$('.information_to').css({
		'display': 'block'
	})
	$('.all_Collect').css({
		'display': 'none'
	})
	$('.medication_S').css({
		'display': 'none'
	})
}

var show_button_four = () => {
	$('.Invite_a_doctor_show').css({
		'display': 'none'
	})
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
	$('.information_to').css({
		'display': 'none'
	})
	$('.all_Collect').css({
		'display': 'block'
	})

	$('.medication_S').css({
		'display': 'none'
	})
}

var show_button_five = () => {
	$('.Invite_a_doctor_show').css({
		'display': 'none'
	})
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
	$('.information_to').css({
		'display': 'none'
	})
	$('.all_Collect').css({
		'display': 'none'
	})

}

//定时器
var a = 10;
var interval;

$('.Push_button').on('click', '.Invite_a_doctor', function() {
	if($(".Invite_a_doctor").html() == "邀请医生") {
		if(!$(".username").attr("data-id")) {
			layer.open({
				title: '系统提示',
				content: '您还没有加入房间,请先加入房间',
				success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
		       }
			});
			return
		}
		show_button_one();
	} else {
		a = 10;
		clearInterval(interval);
		$(".Invite_a_doctor").html("邀请医生");
		let roomid = $(".username").attr("data-id");
		socket.emit("private_data", {
			dataType: 2,
			roomID: roomid,
			socket_id:$(this).attr("socket_id"),
			text: "撤回邀请"
		});
		layer.msg('撤回邀请成功!', {
				icon: 1
			});
	    };
})
var inviteindex=0;
// 点击  邀请医生确定按钮
$('.Invite_a_doctor_show').on('click', '.doctor_submit', function() {
	if(!$('.doctor_select option:selected').attr("data-id")) {
		layer.open({
			title: '系统提示',
			content: '还没有医生在线！',
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
		   }
		});
		return;
	};
	//$(".Invite_a_doctor").attr("disabled", "disabled");
	let doctor = $('.doctor_select option:selected').text();
	layer.msg(`邀请${doctor}成功!`, {
				icon: 1
	});
	$(".Invite_a_doctor,.Undo").attr("socket_id",$('.doctor_select option:selected').attr("data-id"));
	//邀请确认
	socket.emit("inviteroom", {
		socketid: $('.doctor_select option:selected').attr("data-id"),
		roomID: $(".username").attr("data-id"),
		username: $("#name").attr("data-username"),
		roomname:$(".closes").attr("userphone")
	});
	$('span[rooname="' + $(".username").attr("data-id") + '"]').html("已邀请医生");
	if($(".Invite_a_doctor").html() == "邀请医生") {
		interval = setInterval(function() {
			a--;
			if(a == 0) {
				a = 10;
				clearInterval(interval);
				$(".Invite_a_doctor").html("邀请医生");
				$(".Invite_a_doctor").removeAttr("disabled");
				layer.open({
					type: 1,
					title: ['新消息', "background: rgb(240,240,240)"],
					area: ['280px', '180px'],
					shade: 0,
					offset: 'rb',
					anim: 2,
					closeBtn: false,
					content: "<div  style='word-wrap: break-word;margin: 0 auto;width: 200px;text-align: center;margin-top:10px;color: black;'>" + '邀请' + doctor + '医生已超时,是否重新邀请！' + "</div>",
					btn: ['马上处理', '关闭'],
					btn1: function(index) {
						layer.close(index);
						show_button_one()
					},
					btn2: function(index) {
						layer.close(index);
					},
					zIndex: layer.zIndex,
					success: function(layero) {
						layer.setTop(layero); //重点2\
						layero.find(".layui-layer-title").before("<span></span>");
						layero.find(".layui-layer-title").css({
							"font-weight": "500",
							"width": "100%"
						});
						layero.find(".layui-layer-title").addClass("glyphicon glyphicon-cog");
						layero.find(".layui-layer-title").css({
							"font-weight": "500"
						});
						layero.find(".layui-layer-btn").css({
							"border-top": "1px solid rgb(240,240,240)",
							"text-align": "center"
						});
						layero.find(".layui-layer-btn0").css({
							"width": "100px",
							"border-color": "white",
							"background-color": "white",
							"color": "#1abb9c",
							"border-right": "1px solid rgb(240,240,240)"
						});
						layero.find(".layui-layer-btn1").css({
							"width": "100px",
							"border-color": "white",
							"background-color": "white",
							"color": "rgb(145, 141, 141)"
						})
					}
				});
				socket.emit("inviteroomss", {
					socketid: $('.doctor_select option:selected').attr("data-id"),
					roomID: $(".username").attr("data-id"),
					content: false
				});
			} else {
				$(".Invite_a_doctor").html("撤回邀请(" + a + "s)");
			}
		}, 1000);
		//医生接收邀请或者拒绝邀请
		socket.on("inviterooms", (data) => {
			if(data.res) {
				a = 10;
				clearInterval(interval);
				$(".Invite_a_doctor").html("邀请医生");
				$(".Invite_a_doctor").removeAttr("disabled");
				$('span[rooname="' + $(".username").attr("data-id") + '"]').html("已加入");
			} else {
				inviteindex++;
				console.log(inviteindex)
				a = 10;
				clearInterval(interval);
				$(".Invite_a_doctor").html("邀请医生");
				$(".Invite_a_doctor").removeAttr("disabled");
				$('span[rooname="' + $(".username").attr("data-id") + '"]').html("拒绝邀请");
				if(inviteindex==1){
				layer.open({
					type: 1,
					title: ['新消息'],
					area: ['280px', '180px'],
					shade: 0,
					offset: 'rb',
					anim: 2,
					closeBtn: false,
					content: "<div  style='word-wrap: break-word;margin: 0 auto;width: 200px;text-align: center;margin-top:10px;color: black;'>" + '邀请' + doctor + '医生已被拒绝,是否重新邀请！' + "</div>",
					btn: ['马上处理', '关闭'],
					btn1: function(index) {
						layer.close(index);
						show_button_one();
						inviteindex=0;
					},
					btn2: function(index) {
						layer.close(index);
						inviteindex=0;
					},
					zIndex: layer.zIndex,
					success: function(layero) {
						layer.setTop(layero); //重点2\
						layero.find(".layui-layer-title").before("<span></span>");
						layero.find(".layui-layer-title").css({
							"font-weight": "500",
							"width": "100%"
						});
						layero.find(".layui-layer-title").addClass("glyphicon glyphicon-cog");
						layero.find(".layui-layer-title").css({
							"font-weight": "500"
						});
						layero.find(".layui-layer-btn").css({
							"border-top": "1px solid rgb(240,240,240)",
							"text-align": "center"
						});
						layero.find(".layui-layer-btn0").css({
							"width": "100px",
							"border-color": "white",
							"background-color": "white",
							"color": "#1abb9c",
							"border-right": "1px solid rgb(240,240,240)"
						});
						layero.find(".layui-layer-btn1").css({
							"width": "100px",
							"border-color": "white",
							"background-color": "white",
							"color": "rgb(145, 141, 141)"
						})
					}
				});			
				}
			}
		});
	};
	//关闭邀请医生div
	$('.Invite_a_doctor_show').css({
		'display': 'none'
	})
});

socket.on("Undotext", function(data) {
	console.log(data);
	let text="";
	if(data.userrole == 1) {
		text="医生"+data.name
	}
	if(data.userrole == 6) {
		text="助理"+data.name
	};
	layer.open({
		type: 1,
		title: ['新消息'],
		area: ['280px', '180px'],
		shade: 0,
		offset: 'rb',
		anim: 2,
		closeBtn: false,
		content: "<div  style='word-wrap: break-word;margin: 0 auto;width: 200px;text-align: center;margin-top:10px;color: black;' roomID=" + data.data.roomID + ">" + text+data.data.text + '是否重新指派！' + "</div>",
		btn: ['马上处理', '关闭'],
		btn1: function(index) {
			//基本信息
			layer.close(index);
			show_button_two();
		},
		btn2: function(index) {
			layer.close(index);
		},
		zIndex: layer.zIndex,
		success: function(layero) {
			layer.setTop(layero); //重点2\
			$(".Assigned_tothe_doctor").text("指派医生");
			layero.find(".layui-layer-title").before("<span></span>");
			layero.find(".layui-layer-title").css({
				"font-weight": "500",
				"width": "100%"
			});
			layero.find(".layui-layer-title").addClass("glyphicon glyphicon-cog");
			layero.find(".layui-layer-title").css({
				"font-weight": "500"
			});
			layero.find(".layui-layer-btn").css({
				"border-top": "1px solid rgb(240,240,240)",
				"text-align": "center"
			});
			layero.find(".layui-layer-btn0").css({
				"width": "100px",
				"border-color": "white",
				"background-color": "white",
				"color": "#1abb9c",
				"border-right": "1px solid rgb(240,240,240)"
			});
			layero.find(".layui-layer-btn1").css({
				"width": "100px",
				"border-color": "white",
				"background-color": "white",
				"color": "rgb(145, 141, 141)"
			})
		}
	});
});

//医生助理接收指派
socket.on("receive",function(data){
	console.log(data);
	if(data.userrole == 1) {
		text="医生"+data.name
	}
	if(data.userrole == 6) {
		text="助理"+data.name
	};
	layer.open({
		type: 1,
		title: ['新消息'],
		area: ['280px', '180px'],
		shade: 0,
		offset: 'rb',
		anim: 2,
		closeBtn: false,
		content: "<div  style='word-wrap: break-word;margin: 0 auto;width: 200px;text-align: center;margin-top:10px;color: black;' roomID=" + data.data.roomID + ">" + text+data.data.text + '是否重新指派！' + "</div>",
		btn: ['马上处理', '关闭'],
		btn1: function(index) {
			//基本信息
			layer.close(index);
			show_button_two();
		},
		btn2: function(index) {
			layer.close(index);
		},
		zIndex: layer.zIndex,
		success: function(layero) {
			layer.setTop(layero); //重点2\
			layero.find(".layui-layer-title").before("<span></span>");
			layero.find(".layui-layer-title").css({
				"font-weight": "500",
				"width": "100%"
			});
			layero.find(".layui-layer-title").addClass("glyphicon glyphicon-cog");
			layero.find(".layui-layer-title").css({
				"font-weight": "500"
			});
			layero.find(".layui-layer-btn").css({
				"border-top": "1px solid rgb(240,240,240)",
				"text-align": "center"
			});
			layero.find(".layui-layer-btn0").css({
				"width": "100px",
				"border-color": "white",
				"background-color": "white",
				"color": "#1abb9c",
				"border-right": "1px solid rgb(240,240,240)"
			});
			layero.find(".layui-layer-btn1").css({
				"width": "100px",
				"border-color": "white",
				"background-color": "white",
				"color": "rgb(145, 141, 141)"
			})
		}
	});
});

//隐藏药品选择DIV
$('.medication_S').on('click', '.Has_been_on_close', function() {
	$('.medication_S').css({
		'display': 'none'
	})
})

// 点击 邀请医生取消按钮

$('.Invite_a_doctor_show').on('click', '.doctor_determine_', function() {
	$('.Invite_a_doctor_show').css({
		'display': 'none'
	})
})

//采集单上传文件
function creatImg(selfs, thiss) {
	let roomid = $(".closes").attr("data-id");
	var formData = new FormData();
	formData.append('files', selfs[0]);
	if(selfs[0].size / 1000 > 1024 * 5) {
		layer.open({
			title: '系统提示',
			content: '上传的图片不能大于5m,请重新选择图片!',
		});
		return
	};
	$.ajax({
		url: "https://xcx.juseyx.cn/service/uploadimg",
		type: "post",
		cache: false,
		data: formData,
		processData: false,
		contentType: false,
		success: function(res) {
			console.log(res);
			if($(thiss).parent().parent().children().first().children().children().length >= $(thiss).attr("imgsize")) {
				layer.open({
					title: '系统提示',
					content: `您最多只能上传${$(thiss).attr("imgsize")}张图片！`,
				});
				return;
			} else {
				$(thiss).parent().parent().children().first().children().append('<div class="show_imgs"><samp class="deleteimg" onclick="deleteimg(this)">x</samp><img data-magnify="gallery" data-src="' + res.data + '" src="' + res.data + '"  class="layui-upload-img"></div>');
			};
			console.log(upload_img_URL);
		},
		error: function(err) {
			console.log(err)
		}
	})
	//在当前点击的input元素后添加刚刚创建的img图片元素
	// id_.appendChild(img);
};
//删除图片
function deleteimg(thiss){
	$(thiss).parent().remove();
}

// 发送基本表单
function Send_the_basic_information_form() {
	show_button_three();
};

//发送基本表单 是   否 按钮
function determine() {
	//sendoerder
	socket.emit("message", {
		msg: "点击完善基础信息",
		roomID: $(".username").attr("data-id"),
		username: $("#name").attr("data-username"),
		type: 'msg',
		b: 1,
		anonymityImg: "https://xcximg.juseyun.com/Images/servers.png",
		color: false,
		headerimg: null,
		to: null,
		imggs: "",
		id: 0,
		is: $("#name").attr("data-username"),
	});
	html = `<li class="layim-chat-mine">
					<div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${$("#name").attr("data-username")}</i>${moment().format('hh:mm:ss')}</cite>
							</div>
							<div class="layim-chat-text" style="color:white;background-color=;background-color:#1abb9c;">点击完善基础信息</div>
						</li>`
	$('.layim-chat-main>ul').append(html);

	$('.information_to').css({
		'display': 'none'
	})
}

$('.information_to').on('click', '.cancel', () => {
	console.log("否")
	$('.information_to').css({
		'display': 'none'
	})
});

// 选择收集单
function Collect_the_single(e) {
	show_button_four();
	queryorder()

};
var str = "";
//  发送客户  代客户填写
function Send_the_customer(e) {
	//判断收集单id是否为空
	if(!_privateSingles || !subject[_privateSingles]) {
		layer.open({
			title: '系统提示',
			content: '收集单不能为空,请选择收集单!',
			yes: function(index, layero){
			    //按钮【按钮一】的回调
			    layer.close(index);
			},
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
		return;
	};
	$('.all_Collect').css({
		'display': 'none'
	});
	let socket_id = $(".closes").attr("socket_id");
	let roomID = $(".closes").attr("data-id");
	if(user_type == "wx1") {
		layer.open({
			title: '系统提示',
			content: '此用户为小程序用户，只能代填！',
			yes: function(index, layero){
			    //按钮【按钮一】的回调
			    layer.close(index);
			},
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
		return;
	};
	//发送表单数据
	socket.emit("private_msg", {
		socket_id: socket_id,
		roomID: roomID,
		subject: JSON.stringify(subject[_privateSingles]),
		subjectName: subject[_privateSingles][0].formName,
		service: $("#name").attr("data-name"),
		anonymityImg: "https://xcximg.juseyun.com/Images/servers.png"
	});
	//聊天窗口展示
	console.log(subject[_privateSingles][0]);
	//清楚当次表单数据
	subject[_privateSingles] = null;
};

//代填
function Valet_to_fill_out(e) {
	let roomid = $(".closes").attr("data-id");
	if(upload_img_URL[roomid] || suject_Radiosanser[roomid] || suject_Checkboxsanser[roomid] || suject_textareas[roomid]) {
		upload_img_URL[roomid].length = 0; //选择代填清空数组	
		suject_Radiosanser[roomid].length = 0;
		suject_Checkboxsanser[roomid].length = 0;
		suject_textareas[roomid].length = 0;
	};
	if(!_privateSingles) {
		layer.open({
			title: '系统提示',
			content: '收集单不能为空,请选择收集单!',
		});
		return;
	};
	var formDate = '';
	console.log(_privateSingles);
	console.log(subject[_privateSingles]);
	$('div[roomid="' + roomid + '"]').attr("subject_id", _privateSingles);
	let suject_datas = subject[_privateSingles][0].subject;
	if(suject_datas) {
		for(var b = 0; b < suject_datas.length; b++) {
			//console.log(suject_datas[b])
			if(suject_datas[b].type == 1) { //单选
				if(suject_datas[b].select instanceof Array) {
					let str = '';
					for(let a = 0; a < suject_datas[b].select.length; a++) {
						str += `<div class="color_all_style">
								<input type="radio" name="order${b}" class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
					};
					let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'  style="display: flex;	flex-direction: column;" >
					 <p>${b+1}、${suject_datas[b].subjectName}(单选)</p>
					<div class="Day_to_day_A">${str}</div>
					</div>`;
					formDate += formDates;
				};
			};
			if(suject_datas[b].type == 2) { //多选
				if(suject_datas[b].select instanceof Array) {
					let str = '';
					for(let a = 0; a < suject_datas[b].select.length; a++) {
						str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
					};
					let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'  style="display: flex;	flex-direction: column;" >
					<p>${b+1}、${suject_datas[b].subjectName}(多选)</p>
					<div class="Day_to_day_A">${str}</div>
					</div>`;
					formDate += formDates;
				};
			};
			if(suject_datas[b].type == 3) { //简答
				let str = `<textarea name="textareas" class="textarea${b+1}" style='margin-left: -20px;width: 100%;height: 70px;background: white;border-radius: 5px;'></textarea>`
				let formDates = `<div class="user_news_all_"  style="display: flex;	flex-direction: column;"  data_item="${b}" data_index='${suject_datas[b].type}'>
				<p>
				${b+1}、${suject_datas[b].subjectName}(简答)</p>
					<div class="Day_to_day_A">${str}</div>
					</div>`;
				formDate += formDates;
			};
			if(suject_datas[b].type == 4) { //图片
				let str = `<div class="" style=" display: flex;	flex-direction: row;flex-wrap: wrap; " > 
								<div style="height:110px;" >
								    <div class="layui-upload-list" style="height: 93px;margin:0 5px;display: flex;flex-direction: row  "></div>
								</div>
								<div class="layui-upload">
									 <img src="img/uploadimg.png" class="upload_Orderimg"/>
									  <input type="file" name="files"  class="upload_img" imgsize="${suject_datas[b].img}"  onchange="creatImg(this.files,this)" />
								</div>
								
							</div>`
				let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}' style="display: flex;	flex-direction: column;">
				    <p>${b+1}、${suject_datas[b].subjectName}(图片)</p>
					<div class="Day_to_day_A">${str}</div>
					</div>`;
				formDate += formDates;
			};
		};
		$('div[roomid="' + roomid + '"] .men_input_change_three').html(formDate);
	};

	//		if(str == "男科") {
	//			indexs = 1;
	$('div[roomid="' + roomid + '"] .men_input_change').css({
		'display': 'block'
	})
	$('div[roomid="' + roomid + '"] .substitute_women').css({
		'display': 'none'
	})
	$('div[roomid="' + roomid + '"] .diagnosis').css({
		'margin-top': '30px'
	})

	$('div[roomid="' + roomid + '"] .single_submit_S_All').css({
		'display': 'block'
	})
	$('div[roomid="' + roomid + '"] .single_submit_S_All_').css({
		'display': 'none'
	})
	$('div[roomid="' + roomid + '"] .substitute').children().html("");
	$('.all_Collect').css({
		'display': 'none'
	});

};

//修改信息
function modification(e) {
	let roomid = $(e.target).parent().parent().parent().parent().attr('roomid');
	$('div[roomid="' + roomid + '"] .biaodaninfo').css("display", "block");
	$('div[roomid="' + roomid + '"] .drawing_input').css("display", "none");
	//修改按钮显示
	$('div[roomid="' + roomid + '"] .modification').css("display", "none")
	//发送基本信息表单按钮隐藏
	$(".Send_the_basic_information_form").css("display", "block");
	$('div[roomid="' + roomid + '"] input').removeAttr("disabled");

	$('div[roomid="' + roomid + '"] .infoname').val($('div[roomid="' + roomid + '"] .username_S_left').text());
	$('div[roomid="' + roomid + '"] .date').val($('div[roomid="' + roomid + '"] .userdate_S_left').text());
	$('div[roomid="' + roomid + '"] .heights').val($('div[roomid="' + roomid + '"] .height_S_left').text());
	$('div[roomid="' + roomid + '"] .weights').val($('div[roomid="' + roomid + '"] .weight_S_left').text());
	$('div[roomid="' + roomid + '"] .Medical').val($('div[roomid="' + roomid + '"] .input_medical_left').text());
	$('div[roomid="' + roomid + '"] .allergiesed').val($('div[roomid="' + roomid + '"] .input_allergy_left').text());
	$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "80px");

	let html1 = `<div class="gender_all_men">
				<input type="radio" name="men"  value="1" class="radios">
				<span>男</span>
				</div>
				<div class="gender_all_wormen">
				<input type="radio" name="men"  value="2" class="radios">
				<span>女</span>
				</div>`;

	$('div[roomid="' + roomid + '"] .gender_all').children().remove();
	$('div[roomid="' + roomid + '"] .gender_all').html(html1);
	if(gengers == 1) {
		document.getElementsByName("men")[0].checked = "checked";
	} else {
		document.getElementsByName("men")[1].checked = "checked";
	}
};

//  var  roomid_id_s =roomid

//.htmlappend[roomid="${roomid}"] 

//修改信息确定
function btnSubmit(e) {
	event.preventDefault();
	let roomid = $(e.target).parent().parent().parent().parent().parent().parent().parent().attr('roomid');
	//  正则验证  
	//验证数字    
	let infos = ($('div[roomid="' + roomid + '"] .infoname').val())
	let dates = ($('div[roomid="' + roomid + '"] .date').val())
	let heights = ($('div[roomid="' + roomid + '"] .heights').val())
	let weights = ($('div[roomid="' + roomid + '"] .weights').val())
	if(!infos || !dates || !heights || !weights) {
		layer.open({
			title: '系统提示',
			content: '请完善基本信息',
			yes: function(index, layero){
			    //按钮【按钮一】的回调
			    layer.close(index);
			},
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
		return
	};
	let pat_numbers = new RegExp("^[0-9]*[1-9][0-9]*$");
	let pat_undefinds = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]", "i");
	$('div[roomid="' + roomid + '"] .biaodaninfo').css("display", "none");

	$('div[roomid="' + roomid + '"] .drawing_input').css("display", "block");
	//修改按钮显示
	$('div[roomid="' + roomid + '"] .modification').css("display", "block");
	//发送基本信息表单按钮隐藏
	$('div[roomid="' + roomid + '"] .Send_the_basic_information_form').css("display", "none");

	$('div[roomid="' + roomid + '"] .username_S_left').text($('div[roomid="' + roomid + '"] .infoname').val());
	$('div[roomid="' + roomid + '"] .userdate_S_left').text($('div[roomid="' + roomid + '"] .date').val());
	$('div[roomid="' + roomid + '"] .height_S_left').text($('div[roomid="' + roomid + '"] .heights').val());
	$('div[roomid="' + roomid + '"] .weight_S_left').text($('div[roomid="' + roomid + '"] .weights').val());
	$('div[roomid="' + roomid + '"] .input_medical_left').text($('div[roomid="' + roomid + '"] .Medical').val() || "无");
	$('div[roomid="' + roomid + '"] .input_allergy_left').text($('div[roomid="' + roomid + '"] .allergiesed').val() || "无");
	$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "0px");

	let ansRadio = document.getElementsByName('men');
	console.log(ansRadio);
	let text1 = "";
	for(let a = 0; a < ansRadio.length; a++) {
		if(ansRadio[a].checked) {
			text1 = ansRadio[a].value;
		}
	};

	if(text1 == 1) {
		gengers = 1;
		$('div[roomid="' + roomid + '"] .gender_all').children().remove();
		let htmls = '<div class="gender_all_men">';
		htmls += '<span class="all_men">男</span>';
		htmls += '</div>';
		$('div[roomid="' + roomid + '"] .gender_all').append(htmls);
		//$("input").attr("disabled", "disabled");
	} else {
		gengers = 2;
		$('div[roomid="' + roomid + '"] .gender_all').children().remove();
		let htmls = '<div class="gender_all_wormen">';
		htmls += '<span class="wormen">女</span>';
		htmls += '</div>';
		$('div[roomid="' + roomid + '"] .gender_all').append(htmls);
		//$("input").attr("disabled", "disabled");
	};

}
//基本信息取消按钮
function Basic_cancel(e) {
	let roomid = $(e.target).parent().parent().parent().parent().parent().parent().parent().attr('roomid');
	let infos = ($('div[roomid="' + roomid + '"] .infoname').val())
	let dates = ($('div[roomid="' + roomid + '"] .date').val())
	let heights = ($('div[roomid="' + roomid + '"] .heights').val())
	let weights = ($('div[roomid="' + roomid + '"] .weights').val())
	if(!infos || !dates || !heights || !weights) {
		layer.open({
			title: '系统提示',
			content: '请完善基本信息',
		});
		return
	};
	//  正则验证  
	//验证数字    
	var pat_numbers = new RegExp("^[0-9]*[1-9][0-9]*$");

	var pat_undefinds = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]", "i");

	event.preventDefault();
	$('div[roomid="' + roomid + '"] .biaodaninfo').css("display", "none");

	$('div[roomid="' + roomid + '"] .drawing_input').css("display", "block");
	//修改按钮显示
	$('div[roomid="' + roomid + '"] .modification').css("display", "block");
	//发送基本信息表单按钮隐藏
	$('div[roomid="' + roomid + '"] .Send_the_basic_information_form').css("display", "none");
	let ansRadio = document.getElementsByName('men');
	let text1 = "";
	for(let a = 0; a < ansRadio.length; a++) {
		if(ansRadio[a].checked) {
			text1 = ansRadio[a].value;
			console.log(ansRadio[a].value)
		}
	};
	if(text1 == 1) {
		gengers = 1;
		$('div[roomid="' + roomid + '"] .gender_all').children().remove();
		let htmls = '<div class="gender_all_men">';
		htmls += '<span class="all_men">男</span>';
		htmls += '</div>';
		$('div[roomid="' + roomid + '"] .gender_all').append(htmls);
		//$("input").attr("disabled", "disabled");
	} else {
		gengers = 2;
		$('div[roomid="' + roomid + '"] .gender_all').children().remove();
		let htmls = '<div class="gender_all_wormen">';
		htmls += '<span class="wormen">女</span>';
		htmls += '</div>';
		$('div[roomid="' + roomid + '"] .gender_all').append(htmls);
		//$("input").attr("disabled", "disabled");
	}
};

//   代填收集单       生活状态  单选按钮
$('.Day_to_day').on('click', '.input_radio_s', (e) => {
	console.log($(e.target));
})

$('.input_search_classification').click(function() {
	$('#classAll_product').toggle();
})

function Send_the_basic_information_form_drug() {
	//	$('.medication_S').css('display', 'block');
	//	show_button_five()
	let roomid = $(".username").attr("data-id");
	$('.midmed').html($('div[roomid="' + roomid + '"] .Scroll_area').html());
	var spanlist = $('div[roomid="' + roomid + '"] .Scroll_area span b');
	for(var i = 0; i < spanlist.length; i++) {
		$($('.midmed span b')[i]).next().val(parseInt($(spanlist[i]).next().val()));
	}
	$('.delbtn').on('click', function(e) {
		console.log(e)
		$(e.target).parent('span').remove();
	})
};

// 二级
$(() => {
	$('.click_first_classification').click(function(e) {
		//  获取 商品ID
		if($(this).children('.status').text() == "+") {
			$(this).siblings('ul').css({
				'display': 'block'
			})
			$('.status').html("-")
		} else
		if($(this).children('.status').text() == "-") {
			$(this).siblings('ul').css({
				'display': 'none'
			})
			$('.status').html("+")
		}
	})
})

// 三级
$('.click_two_classification').click(function() {
	//   console.log($(this).siblings())
	if($(this).children('.status_fitst_two').text() == "+") {
		$(this).siblings('ul').css({
			'display': 'block'
		})
		$('.status_fitst_two').html("-")
	} else
	if($(this).children('.status_fitst_two').text() == "-") {
		$(this).siblings('ul').css({
			'display': 'none'
		})
		$('.status_fitst_two').html("+")
	}

})

function getObjectURL(file) {
	var url = null;
	if(window.createObjectURL != undefined) {
		url = window.createObjectURL(file)
	} else if(window.URL != undefined) {
		url = window.URL.createObjectURL(file)
	} else if(window.webkitURL != undefined) {
		url = window.webkitURL.createObjectURL(file)
	}
	return url
};

function onKeyPress(event) {
	console.log(event)
	event = event || window.event;
	if(event.keyCode == 13) {
		event.returnValue = false;
		let username = $("#name").attr("data-username");
		event.preventDefault();
		var html = "";
		let text = $('.textarea_sends').val().trim();
		if(text.length > 500) {
			layer.open({
				title: '系统提示',
				content: '发送消息内容超长,请分条发送',
			});
			return;
		};
		if(text == null || text == "") {
			$('.Prompt_box').css({
				'display': 'block'
			})
			setTimeout(() => {
				$('.Prompt_box').css({
					'display': 'none'
				})
			}, 1500)
		} else {
			let time = new Date();
			//html += '<li class="say_layout"><div class="Tosay"><div class="right-Text"><div class="left-d"><span class="span_time">' + "  " + username + "  " + time.getHours() + ":" + (time.getMinutes().toString().length == 1 ? "0" + time.getMinutes() : time.getMinutes()) + ":" + (time.getSeconds().toString().length == 1 ? "0" + time.getSeconds() : time.getSeconds()) + '</span><div  class="a3">' + text + '</div></div></div></div></li>';
			html = `<li class="layim-chat-mine">
					<div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${$("#name").attr("data-username")}</i>${moment().format('hh:mm:ss')}</cite>
							</div>
							<div class="layim-chat-text" style="color:white;background-color=;background-color:#1abb9c;">${text}</div>
						</li>`
			$('.layim-chat-main>ul').append(html);
			$('#textarea').val("");
			socket.emit("message", {
				msg: text,
				roomID: $(".username").attr("data-id"),
				username: $("#name").attr("data-username"),
				userRole:$("#name").attr("userrole"),
				type: 'string',
				b: 1,
				anonymityImg: "https://xcximg.juseyun.com/Images/servers.png",
				color: false,
				headerimg: null,
				to: null,
				imggs: "",
				id: 0,
				is: $("#name").attr("data-username"),
			});
			let div = document.getElementsByClassName('chat-thread')[0];
			div.scrollTop = div.scrollHeight;
			//发送信息当前房间列表置前
			roomlist();
		}
	}
}

socket.on('chat msg', function(data) {
	var html = "";
	for(var i = 0; i < data.length; i++) {
		console.log(data[i])
		var item = data[i]
		html += `
            <li class="say_layout">                     
              <div class="Tosay">                
              <div class="${item.b==1?'left-Text':'right-Text'}">
               <div class="left-d">    
                 <!-- 字的外边框  -->
                  <div class="a2-img ${item.b==1?'ToRight':'ToLeft'}" data-b='${item.b}' catchtap='userTo'>
                   <img src="${item.headerImg}" class="a2-img ${item.b==1?'block':'none'}">
                      </div>
                           <!--  ${item.b==2?'font-top':'pp'} -->
                              <div class="font-top">
                               <!-- 气泡 -->                     
                              <div class="${item.b==1?'font-topss':'font-tops'}"></div>
                              <!-- ${item.b==2?'fontOne':'fontTwo'}  -->
                                <div class="a3" style="color:${item.color==true?'red':'black'}" data-index="${index}" catchtap='jump'>                   
                                  <div wx:if="${item.color==false}" style='color:${item.text=="男科"||item.text=="妇科"?"red":"black"};text-decoration:${item.text=="男科"||item.text=="妇科"?"underline":"none"}'
                                     data-to="${item.to}"
                                                 catchtap='toinput'>
                                                         ${item.text}
                                                              </div>
                                                               <!-- <view >
                                                                  ${item.text}
                                                                    </view> -->
                                             <!--  发送图片 判断 -->                  
                                            <div style='display:${item.imggs==""||item.imggs==null?"none":"block"}' class='showImg_All'>                    
                                                  <img class='upImgss' src='${item.imggs}' data-img="${item.imggs}" catchtap='watchImg'>                     
                                                       </div>
                                                            <!-- <web-view wx:if="${toH5}" src="${urls}"></web-view> -->
                                                                           <!-- 小卡片 -->
                                                                       <!--                                                                                 
                                                                 <div class='card' wx:if="${item.color}">
                                                                                                       
                                                                                                       
                                                                   小卡片
                                                                      </div> -->
                                                                          </div>
                       
                                                                                        </div>
                                                                               <!--  -->
                                                                                  <div class="a2-img ${item.b==1?'ToRight':'ToLeft'}" data-b='${item.b}' catchtap='doctorTo'>
                                                                                     <img src="${item.headerImg}" class="a2-img ${item.b==2?'block':'none'}">
                                                                                  </div>
                                                                                    <!--  -->
                                                                      </div>
                                                  </div>
                                     </div>                  
                        </li>
                 `
	}
	$('.chat-thread').append(html)
	//    socket.emit('chat msg',data)
})

const all_url = {
	url: "http://10.10.10.98:9000/ajaxs",
	type: "post"
};

function b(url) {
	return new Promise((reslove, reject) => {
		let url = all_url.url
		let type = all_url.type
		$.ajax({
			url: url,
			type: type,
			data: {
				a: 1
			},
			success: data => {
				if(data) {
					reslove(data)
				}

			},
			error: err => {
				reject(err)
			}
		})

	}).then((data) => {
		console.log(data)
	}).catch((err) => {
		console.log(err)
	})
};
//科室
$('.select_menAnd_wormen').change((e) => {
	//alert($('#select_menAnd_wormen option:selected').text());
	//console.log($('#select_menAnd_wormen option:selected').text())
	let roomid = $(".username").attr("data-id");
	str = $('#select_menAnd_wormen option:selected').text();
	let selectid = $('#select_menAnd_wormen option:selected').attr('id');
	//收集单数据
	let newhtml = '<option value="" selected="true" disabled="true">请选择采集单</option>';
	if(oldtree[selectid].children) {
		for(let a = 0; a < oldtree[selectid].children.length; a++) {
			newhtml += `<option value="${oldtree[selectid].children[a].value}">${oldtree[selectid].children[a].label}</option>`;
		};
		$(".Disease_class").html(newhtml);
	} else {
		$(".Disease_class").html('<option value="" selected="true" disabled="true">请选择采集单</option>');
	}
});

//采集单id
$('#documents').change((e) => {
	console.log($('#documents option:selected').val());
	_privateSingle = $('#documents option:selected').val();
	$.ajax({
		url: serverURL + "form",
		type: "get",
		dataType: "json",
		data: {
			classifyId: _privateSingle
		},
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res);
			let select_data = res.data;
			let newhtml = '<option value="" selected="true" disabled="true">请选择采集单详情</option>';
			if(res.code == 200) {
				for(let a = 0; a < select_data.length; a++) {
					newhtml += `<option value="${select_data[a]._id}">${select_data[a].formName}</option>`;
					if(!subject[select_data[a]]) {
						subject[select_data[a]._id] = [];
						subject[select_data[a]._id].push(select_data[a]);
					};
				};
				$(".particulars_Order").html(newhtml);
			};

		},
		error: function(err) {

		}
	})
});
//收集单详情
$('.particulars_Order').change((e) => {
	_privateSingles = $('.particulars_Order option:selected').val();
});

//药品分类
$.ajax({
	url: "https://xcxgoods.juseyx.cn/categories/GetCategoryList",
	dataType: "json",
	type: "post",
	async: true,
	data: {
		categoryname: "",
		isenabled: 1
	},
	success: function(res) {
		//展示一级分类
		var classification = res.data
		var html_ = "";
		for(let i = 0; i < classification.length; i++) {
			html_ +=
				`
				                               <li>
													<div class="click_first_classification" data-productID="${classification[i].categoryid}"  data-index="${i}">
														<span class="first_classification status">+</span>
														<span class="first_classification">${classification[i].categoryname}</span>
													</div>												
												</li>
			`
		}

		$('.classification_threes_all').append(html_)

	},
	error: function(err) {
		console.log(err)
	}
});

var index_one;

//  二级分类
$('.classification_threes_all').on('click', '.click_first_classification', function() {

	console.log($(this)[0].dataset.index)

	// 获取 下标
	var index_ = $(this)[0].dataset.index

	var product_ID = $(this)[0].dataset.productid

	console.log($(this)[0].dataset.productid)

	index_one = index_

	//获取子元素的文本
	var text_class_one = $(this).children('.status').text()

	if(text_class_one == "+") {
		$('.classification_two_all').css({
			'display': 'block'
		})
		$(this).children('.status').html('-')
		$(this).parent('li').siblings().find('.click_first_classification .status').text('+')
		// console.log("加号")
	} else
	if(text_class_one == "-") {
		$('.classification_two_all').css({
			'display': 'none'
		})
		//      	     $('.classification_three_all_').css({'display':'none'})
		$(this).children('.status').html('+')
		$('.classification_three_all_').css({
			'display': 'none'
		})
		// console.log("减号")
	}

	$('.classification_two_all').children('li').remove()

	$.ajax({
		url: "https://xcxgoods.juseyx.cn/categories/GetCategoryList",
		dataType: "json",
		type: "post",
		async: true,
		data: {
			categoryname: "",
			isenabled: 1
		},
		success: function(res) {
			console.log(res.data)

			const two_class = res.data
			console.log(two_class[index_].children)
			const two_class_children = two_class[index_].children

			var html_l = "";

			for(let a = 0; a < two_class_children.length; a++) {

				console.log(a)

				html_l +=
					`
          	            <li>
													<div class="click_first_classification" data-productID="${two_class_children[a].categoryid}"  data-index="${a}">
														<span class="first_classification status">+</span>
														<span class="first_classification">${two_class_children[a].categoryname}</span>

													</div>

												
						</li> 
          	      `

			}

			$('.classification_two_all').append(html_l)

		},
		error: function(err) {
			console.log(err)
		}

	})

	//      渲染对应的商品 
	$('.product_show_alls').children().remove()

	$.ajax({
		type: "post",
		url: "https://xcxgoods.juseyx.cn/products/GetYyReceptionGoods",
		data: {
			categoryid: product_ID,
			brandid: "",
			isdrugstatus: "N",
			pageindex: 1,
			pagesize: 10,
			SortBy: "addeddate",
			Desc: true,
		},
		success: function(res) {

			console.log(res.data)
			//  一级分类

			let one_classification = res.data

			var one_classification_ = "";

			for(let i = 0; i < one_classification.length; i++) {

				one_classification_ +=
					`
													 <li>
													 <span class="add_label" data-isdrugstatus="${one_classification[i].isdrugstatus}" data-productName="${one_classification[i].productname}"  data-productID="${one_classification[i].categoryid}"  data-srcs="${one_classification[i].goodlistimageurl}${one_classification[i].gooddetailimagename1}"  >+</span>
											
													 <span class="product_add_name"><a style="cursor: pointer;" title="${one_classification[i].productname}">${one_classification[i].productname}</a></span>
													 <!-- 商品图片 -->
													 <img src="${one_classification[i].goodlistimageurl}${one_classification[i].gooddetailimagename1}" class="product_img_s" alt="">
													 <!-- 通用名 -->
													 <span class="Common_name" ><a style="cursor: pointer;" title="${one_classification[i].productname}">${one_classification[i].productname}</a></span>
		 
													 <!-- 规格 -->
													 <span class="specification" ><a style="cursor: pointer;" title="${one_classification[i].specification}">${one_classification[i].specification}</a></span>
		 
													 <!-- 品牌 -->
		 
													 <span class="brands" ><a style="cursor: pointer;" title="${one_classification[i].brandname}">${one_classification[i].brandname}</a></span>
		 
													 <!-- 生产厂家 -->
		 
													 <span  class="manufacturer_" ><a style="cursor: pointer;" title="${one_classification[i].manufacturer}">${one_classification[i].manufacturer}</a></span>
		 
												 </li>
													 `
			}

			$('.product_show_alls').append(one_classification_)
			//  alert("成功")
		},
		error: function(err) {

			// alert("错误")
		}
	})

})

// 二级分类

$('.classification_two_all').on('click', '.click_first_classification', function() {

	var index__ = $(this)[0].dataset.index
	var product_ID = $(this)[0].dataset.productid

	console.log($(this)[0].dataset.productid)

	//获取子元素的文本

	//获取子元素的文本
	var text_class_ones = $(this).children('.status').text()

	if(text_class_ones == "+") {
		$('.classification_three_all_').css({
			'display': 'block'
		})
		$(this).children('.status').html('-')
		$(this).parent('li').siblings().find('.click_first_classification .status').text('+')

		console.log("加号")
	} else
	if(text_class_ones == "-") {
		$('.classification_three_all_').css({
			'display': 'none'
		})
		$(this).children('.status').html('+')
		console.log("减号")
	}

	$('.classification_three_all_').children('li').remove()
	$.ajax({
		type: "post",
		url: "https://xcxgoods.juseyx.cn/categories/GetCategoryList",
		dataType: "json",

		async: true,
		data: {
			categoryname: "",
			isenabled: 1
		},
		success: function(res) {
			console.log(res)
			const two_class_ = res.data[index_one].children[index__].children
			var html_t = "";
			for(let e = 0; e < two_class_.length; e++) {
				html_t +=
					`
		      	              <li>
													<div class="click_first_classification" data-productID="${two_class_[e].productid}"     data-index="${e}">
														<span class="first_classification status"  style="display:none">+</span>

														<span class="first_classification">${two_class_[e].categoryname}</span>

													</div>								
						  </li> 
		      	        `
			}
			$('.classification_three_all_').append(html_t)
		}
	})

	//    渲染 二级分类的商品
	//      渲染对应的商品 
	$('.product_show_alls').children().remove()

	$.ajax({
		type: "post",
		url: "https://xcxgoods.juseyx.cn/products/GetYyReceptionGoods",
		data: {
			categoryid: product_ID,
			brandid: "",
			isdrugstatus: "N",
			pageindex: 1,
			pagesize: 10,
			SortBy: "addeddate",
			Desc: true,
		},
		success: function(res) {

			console.log(res.data)
			//  一级分类

			let one_classification = res.data

			var one_classification_ = "";

			for(let i = 0; i < one_classification.length; i++) {

				one_classification_ +=
					`
											   <li>
											   <span class="add_label" data-isdrugstatus="${one_classification[i].isdrugstatus}" data-productName="${one_classification[i].productname}" data-productID="${one_classification[i].productid}" data-srcs="${one_classification[i].goodlistimageurl}${one_classification[i].gooddetailimagename1}" >+</span>
											   <!-- 名称 -->
											   <span class="product_add_name"><a style="cursor: pointer;" title="${one_classification[i].productname}">${one_classification[i].productname}</a></span>
											   <!-- 商品图片 -->
											   <img src="${one_classification[i].goodlistimageurl}${one_classification[i].gooddetailimagename1}" class="product_img_s" alt="">
											   <!-- 通用名 -->
											   <span class="Common_name" ><a style="cursor: pointer;" title="${one_classification[i].productname}">${one_classification[i].productname}</a></span>
   
											   <!-- 规格 -->
											   <span class="specification" ><a style="cursor: pointer;" title="${one_classification[i].specification}">${one_classification[i].specification}</a></span>
   
											   <!-- 品牌 -->
   
											   <span class="brands" ><a style="cursor: pointer;" title="${one_classification[i].brandname}">${one_classification[i].brandname}</a></span>
   
											   <!-- 生产厂家 -->
   
											   <span  class="manufacturer_"><a style="cursor: pointer;" title="${one_classification[i].manufacturer}">${one_classification[i].manufacturer}</a></span>
   
										   </li>
											   `
			}

			$('.product_show_alls').append(one_classification_)
			//    alert("成功")
		},
		error: function(err) {

			//   alert("错误")
		}
	})
})
//  点击搜索 搜索对应药品
$('.medication_S').on('click', '.medication_search', function() {
	//	console.log($(this))
	//	console.log($('.medication_S_classification .input_search_s').val())
	let search_text = $('.medication_S_classification .input_search_s').val()
	$.ajax({
		url: "https://xcxgoods.juseyx.cn/products/GetYyReceptionGoods",
		data: {
			pagesize: 20,
			pageindex: 1,
			ReceptionSearch: search_text,
			brandid: null,
			isdrugstatus: "N",
			SortBy: "addeddate",
			Desc: true
		},
		type: "post",
		success: res => {
			console.log(res)
			//   全部数组
			var product_name_all = res.data
			var product_name_all_ = "";
			$('.product_show_alls').children().remove()
			for(let i = 0; i < product_name_all.length; i++) {
				product_name_all_ +=
					`
										   <li>
										   <span class="add_label" data-isdrugstatus="${product_name_all[i].isdrugstatus}" data-productName="${product_name_all[i].productname}"  data-productID="${product_name_all[i].productid}" data-srcs="${product_name_all[i].goodlistimageurl}${product_name_all[i].gooddetailimagename1}">+</span>
										   <!-- 名称 -->
										   <span class="product_add_name"><a style="cursor: pointer;" title="${product_name_all[i].productname}">${product_name_all[i].productname}</a></span>
										   <!-- 商品图片 -->
										   <img src="${product_name_all[i].goodlistimageurl}${product_name_all[i].gooddetailimagename1}" class="product_img_s" alt="">
										   <!-- 通用名 -->
										   <span class="Common_name"><a style="cursor: pointer;" title="${product_name_all[i].productname}">${product_name_all[i].productname}</a></span>

										   <!-- 规格 -->
										   <span class="specification"><a style="cursor: pointer;" title="${product_name_all[i].specification}">${product_name_all[i].specification}</a></span>

										   <!-- 品牌 -->

										   <span class="brands"><a style="cursor: pointer;" title="${product_name_all[i].brandname}">${product_name_all[i].brandname}</a></span>

										   <!-- 生产厂家 -->

										   <span  class="manufacturer_"><a style="cursor: pointer;" title="${product_name_all[i].manufacturer}">${product_name_all[i].manufacturer}</a></span>

									   </li>
										   
										   `

			}

			$('.product_show_alls').append(product_name_all_)
			// alert("成功")

		},
		error: err => {
			//  alert("失败")
		}
	})
})

$(function() {
	$.ajax({
		type: "post",
		url: "https://xcxgoods.juseyx.cn/categories/GetCategoryList",
		dataType: "json",
		timeout: 5000,
		traditional: true,
		data: {
			categoryname: "",
			isenabled: 1
		},
		async: true,
		success: function(res) {
			console.log(res)
		},
		error: function(err) {
			console.log(err)
		}
	});
});

//获取 文本框的长度
function onkeyups(e) {
	let roomid = $(".username").attr("data-id");
	let length_ = e.length
	$("div[roomid='" + roomid + "'] .length_s_all").html(length_);
}

//添加 药品标签 进入
var suggestdrug = {}; //建议用药
$('.product_show_alls').on('click', '.add_label', function() {
	let roomid = $(".username").attr("data-id");
	let div1 = document.getElementsByClassName('apendhtml');
	for(let a = 0; a < div1.length; a++) {
		if($(div1[a]).attr("roomid") == roomid) {
			div1[a].scrollTop = div1[a].scrollHeight;
		}
	}
	let productid = $(this)[0].dataset.productid; //药品ID
	let productname = $(this)[0].dataset.productname; //药品名称
	let isdrugstatus = $(this)[0].dataset.isdrugstatus; //是否处方药

	if(isdrugstatus == "Y") { ////N-非处方药 Y-处方药(时空)
		layer.open({
			title: '系统提示',
			content: '此药品为处方药,您不能选择',
		});
		return;
	}
	let img = $(this)[0].dataset.srcs;
	if(!suggestdrug[roomid]) {
		suggestdrug[roomid] = [];
	};
	let pars = {
		productid: productid,
		productname: productname,
		isdrugstatus: isdrugstatus,
		img: img,
		count: 1
	}
	let finda = 0;
	if(suggestdrug[roomid].length > 0) {
		for(let a = 0; a < suggestdrug[roomid].length; a++) {
			if(suggestdrug[roomid][a].productid == pars.productid) {
				finda = a + 1;
			}
		}
		if(finda > 0) {
			suggestdrug[roomid][finda - 1].count++;
		} else {
			pars.count = 1;
			suggestdrug[roomid].push(pars)
		}
	} else {
		suggestdrug[roomid].push(pars)
	}
	console.log(suggestdrug[roomid])
	let html_ = "";
	for(let p = 0; p < suggestdrug[roomid].length; p++) {
		html_ +=
			`			  <!-- 标签展示 -->
				  <div class="Drug_labels_all_">
				                                  <div class="Drug_labels_all_">
                                               
                                                                        <div class="Drug_labels_all_s"  data-productID="${suggestdrug[roomid][p].productid}">
                                                                                <!-- 删除标签 -->
                                                                                 
                                                                       <a href="http://47.97.17.157:3000/html/Details.html?productId=${suggestdrug[roomid][p].productid}" title=" ${suggestdrug[roomid][p].productname}   " target="_blank">  ${suggestdrug[roomid][p].productname}   </a>
                                                                        </div>
                                                                        <!-- <span class="close_Drug">X</span> -->
                                                                        <!--  输入框  -->
                                                                        <input type="number" style=" " data-productID="${suggestdrug[roomid][p].productid}" class="number_select_" value="${suggestdrug[roomid][p].count}" onblur="onBlur(event)">

                                                                        <img src="./img/delete_.png"   class="img_delete close_Drug" alt="" data-index="${p}">
                                              </div>						
				  </div>				 				     
				  `

	}
	$("div[roomid='" + roomid + "'] .Drug_labels .Scroll_area").html(html_);
	console.log(suggestdrug[roomid])

	// dianji  shanchu 

	//****************************  close-----

	$('.medication_S').on('click', '.Has_been_on_close', function() {

		$(".medication_S").css({
			'display': 'none'
		})
	})
	$('.img_delete').click(function(e) {
		console.log(suggestdrug[roomid])
		console.log($(e.target).parents('.Drug_labels_all_'))
		console.log($(e.target)[0].dataset.index)

		let index = $(e.target)[0].dataset.index

		suggestdrug[roomid].splice(index, 1)

		console.log(suggestdrug[roomid])

		$(e.target).parents('.Drug_labels_all_').remove()
	})
	//	console.log(suggestdrug)
	//	console.log(arr_all_show_)
});
//更改药品数量
function onBlur(e) {
	let product_id = $(e.target).attr('data-productID'); //药品id
	let roomid = $(".username").attr("data-id"); //房间id
	let values = $(e.target).val(); //输入框数值
	if(suggestdrug[roomid]) { //药品数组
		for(let a = 0; a < suggestdrug[roomid].length; a++) {
			if(suggestdrug[roomid][a].productid == product_id) {
				suggestdrug[roomid][a].count = values;
			}
		}
	}
};
$('.chat-thread').on('click', '.chatimg', function() {
	console.log($(this)[0].attributes[1].nodeValue)

	let img_url_ = $(this)[0].attributes[1].nodeValue

	$('.Reading_pictures_show').css({
		'display': 'block'
	})
	$('.Reading_pictures_show').addClass('animated bounceInLeft')

	$('.Reading_pictures').attr('src', img_url_)
})
// 关闭图片
$('.Reading_pictures_show').on('click', '.close_Reading_pictures_show_', function() {

	$(this).parent().parent().css({
		'display': 'none'
	})

});
//代填
function man_confirm(event) {
	console.log(subject[_privateSingles])
	let roomid = $(".username").attr("data-id");
	var divcc = $('div[roomid="' + roomid + '"] .men_input_change_three .user_news_all_');
	
	let infos = ($('div[roomid="' + roomid + '"] .username_S_left').text())
	let dates = ($('div[roomid="' + roomid + '"] .riqi').text())
	let heights = ($('div[roomid="' + roomid + '"] .height_S_left').text())
	let weights = ($('div[roomid="' + roomid + '"] .weight_S_left').text())
	if(!infos || !dates || !heights || !weights) {
		layer.open({
			title: '系统提示',
			content: '请完善基本信息',
		  success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
		   }
		});
		return
	};
	for(var p = 0; p < divcc.length; p++) {
		if($(divcc[p]).attr('data_index') == 1) {
			var radios = $('div[roomid="' + roomid + '"] div[data_item="' + p + '"] input[type="radio"]');
			for(var p1 = 0; p1 < radios.length; p1++) {
				if(radios[p1].checked) {
					subject[_privateSingles][0].subject[p].select[p1].checked = true;
				} else {
					subject[_privateSingles][0].subject[p].select[p1].checked = false;
				};
			};
		};
		if($(divcc[p]).attr('data_index') == 2) {
			var checkboxs = $('div[roomid="' + roomid + '"] div[data_item="' + p + '"] input[type="checkbox"]');
			console.log(checkboxs.length);
			for(var p2 = 0; p2 < checkboxs.length; p2++) {
				if(checkboxs[p2].checked) {
					subject[_privateSingles][0].subject[p].select[p2].checked = true;
				} else {
					subject[_privateSingles][0].subject[p].select[p2].checked = false;
				};
			}
		};
		if($(divcc[p]).attr('data_index') == 3) {
			var txt = $(divcc[p]).children().children().val();
			subject[_privateSingles][0].subject[p].describe = txt;
		};
		if($(divcc[p]).attr('data_index') == 4) {
			var imgsize = $('div[roomid="' + roomid + '"] div[data_item="' + p + '"] .show_imgs');
			let imgArr = [];
			for(let a = 0; a < imgsize.length; a++) {
				imgArr.push($(imgsize[a]).children("img").attr("src"));
			};
			subject[_privateSingles][0].subject[p].img = imgArr || [];
		};
	};
	console.log(subject[_privateSingles][0]);
	event.preventDefault();
	$('div[roomid="' + roomid + '"] .men_input_change input[type="radio"]').attr("disabled", "disabled")
	$('div[roomid="' + roomid + '"] .men_input_change input[type="checkbox"]').attr("disabled", "disabled");
	$('div[roomid="' + roomid + '"] .men_input_change .upload_Orderimg').css("display", "none");
	$('div[roomid="' + roomid + '"] .men_input_change textarea').attr("disabled", "disabled");
	
	$('div[roomid="' + roomid + '"] .deleteimg').hide();//隐藏图片删除按钮
	sendToAssDoc();
};
//修改表单代填信息
function modifications(e) {
	let roomid = $(".username").attr("data-id");
	event.preventDefault();
	$('div[roomid="' + roomid + '"] .deleteimg').show();//显示图片删除按钮
	$('div[roomid="' + roomid + '"] .men_input_change input[type="radio"]').removeAttr("disabled");
	$('div[roomid="' + roomid + '"] .men_input_change input[type="checkbox"]').removeAttr("disabled");
	$('div[roomid="' + roomid + '"] .men_input_change .upload_Orderimg').css("display", "block");
	$('div[roomid="' + roomid + '"] .men_input_change textarea').removeAttr("disabled");
}
// 指派医生
$('.Push_button').on('click', '.Assigned_tothe_doctor', function() {
	let roomid = $(".username").attr("data-id");
	let infos = ($('div[roomid="' + roomid + '"] .username_S_left').text())
	let dates = ($('div[roomid="' + roomid + '"] .userdate_S_left').text())
	let heights = ($('div[roomid="' + roomid + '"] .height_S_left').text())
	let weights = ($('div[roomid="' + roomid + '"] .weight_S_left').text())
	if(!roomid || !infos || !dates || !heights || !weights) {
		layer.open({
			title: '系统提示',
			content: '请完善基本信息以及基本情况收集单',
			yes: function(index, layero){
			    //按钮【按钮一】的回调
			    layer.close(index);
			},
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
		return;
	};
	if($(this).html() != "指派医生") {
		layer.msg('您已经指派,不能重新指派！', {
			icon: 2,
			time: 2000, //2秒关闭（如果不配置，默认是3秒）
		}, function(index) {
			console.log($(this))
		});
	} else {
		//基本信息
		show_button_two();
	}
});

var msg = window.sessionStorage['user_msg'];
msg = JSON.parse(msg);
// 点击 指派确定医生按钮
$('.assign_a_doctor_show').on('click', '.doctor_yaoqing', function() {
	let roomid = $(".username").attr("data-id");
	if(!($("div[roomid='" + roomid + "'] .infoname").val()) || !($("div[roomid='" + roomid + "'] .username_S_left").text())) {
		$('.assign_a_doctor_show').css({
			'display': 'none'
		})
	};
	//判断数据是否满足要求
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
	let username = $("div[roomid='" + roomid + "'] .username_S_left").text();
	let data = $("div[roomid='" + roomid + "'] .userdate_S_left").text();
	let height = $("div[roomid='" + roomid + "'] .height_S_left").text();
	let weight = $("div[roomid='" + roomid + "'] .weight_S_left").text();
	let medical = $("div[roomid='" + roomid + "'] .input_medical_left").text();
	let allergy = $("div[roomid='" + roomid + "'] .input_allergy_left").text();
	let gender_s = $("div[roomid='" + roomid + "'] .all_men").html() || $(".apendhtml[roomid='" + roomid + "'].wormen").html();
	let answer = [];
	let socketid = $('.yaoqing option:selected').attr("data-id");
	let doctorname = $('.yaoqing option:selected').html();
	let userid = $('.yaoqing option:selected').attr("data-userid");
	let userrole = $('.yaoqing option:selected').attr("data-userrole");
	if(!socketid || !doctorname || !userid || !userrole) {
		layer.open({
			title: '系统提示',
			content: '暂无在线的医生或者医生助理',
			success: function(layero) {
						 layero.find(".layui-layer-btn0").css({
						 	"border-color":"#1abb9c",
						 	"background-color":"#1abb9c"
						 })	
			}
		});
		return;
	};
	$(".Invite_a_doctor,.Undo").attr("socket_id",socketid);
	//系统诊断
	let systenm = $("div[roomid='" + roomid + "'] .System_in_the_diagnosis_of").text();
	//客服汇总
	let servicetext = $("div[roomid='" + roomid + "'] .service_of_").val();

	//建议用药
	//let suggestdrug=[];
	let datapars = {
		_id: $("div[roomid='" + roomid + "']").attr("_id"),
		userid: $(".closes").attr("data-id"), //用户id 商城登陆用户id 小程序openid
		mesId: $("div[roomid='" + roomid + "']").attr("uderinfo_id"),
		name: username, //姓名
		birthday: data, //出生日期
		gender: (gender_s == "男" ? 1 : 0), //性别
		height: height, //身高
		weight: weight, //体重
		medicalHistory: medical, //病史
		allergy: allergy, //过敏史
		serverSuggest: servicetext,
		serverId: $("#name").attr("data-name"),
		serverName: $("#name").attr("data-name"),
	};
	if(subject[_privateSingles]) {
		datapars.information = JSON.stringify(subject[_privateSingles][0]);
		datapars.informations = JSON.stringify(subject[_privateSingles]);
	};
	if(userrole == 1) {
		datapars.doctorName = doctorname;
		datapars.receiveId = userid;
	} else if(userrole == 6) {
		datapars.assistantName = doctorname;
		datapars.receiveId = userid;
	};
	let span = $("div[roomid='" + roomid + "'] .Scroll_area>span>b");
	var suggestdrugs = [];
	if(span.length > 0) {
		for(var i = 0; i < span.length; i++) {
			suggestdrugs[i] = {
				productid: $(span[i]).attr('pid'),
				productname: $(span[i]).text(),
				isdrugstatus: $(span[i]).attr('isdrugstatus'),
				img: $(span[i]).attr('img'),
				marketprice: $(span[i]).attr('marketprice'),
				costprice: $(span[i]).attr('costprice'),
				count: $(span[i]).next('input').val(),
			};
		};
		datapars.serMedicinal = JSON.stringify(suggestdrugs) //选择的药品
	} else {
		datapars.serMedicinal = JSON.stringify([]); //药品为空
	};
	datapars.state = '待处理';
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serverURL + "sendToAssDoc",
		traditional: true,
		type: "post",
		dataType: "json",
		data: datapars,
		async: true,
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				if(res._id) {
					socket.emit("assigndoctor", {
						socketid: socketid,
						username: $("#name").attr("data-name"),
						roomID: $(".username").attr("data-id"),
						_id: res._id,
					});
					//缓存用户本次问诊数据
					datapars._id = res._id;
					datapars.expiration_time = null;
					datapars.systenm = systenm;
					datapars.servicetext = servicetext;
					datapars.subject_id = $('div[roomid="' + roomid + '"]').attr("subject_id");
					datapars.receiveId=userid;
					$('div[roomid="' + roomid + '"]').attr("receiveId",userid);
					let pars = {
						roomname: roomid,
						content: JSON.stringify(datapars)
					};
					if(subject[_privateSingles]) {
						$.ajax({
							url: serviceURL + "temporary",
							type: "post",
							dataType: "json",
							data: pars,
							headers: {
								'Authorization': 'Bearer ' + msg.token
							},
							success: function(res) {
								console.log(res);
							},
							error: function(err) {
								console.log(err)
							}
						});
					}
					//审核状态
					if(suggestdrug[roomid]) {
						suggestdrug[roomid].length = 0; //清空数组
					};
					if(!auditResult_id[roomid]) {
						auditResult_id[roomid] = res._id;
						let storage = window.sessionStorage;
						storage.setItem("auditid", JSON.stringify(auditResult_id));
					};
					//系统诊断
				};
//				layer.open({
//					title: '系统提示',
//					content: '指派医生成功',
//					success: function(layero) {
//						 layero.find(".layui-layer-btn0").css({
//						 	"border-color":"#1abb9c",
//						 	"background-color":"#1abb9c"
//						 })	
//				    }
//				});
				layer.msg(`指派医生成功!`, {
							icon: 1
				});
				//指派医生成功 
				assigned_doctor.push(roomid);
				//				$(".Assigned_tothe_doctor").text("医生审核中");
				//				$("div[roomid='" + roomid + "'] .modification").css("display", "none");
				//				$(".Assigned_tothe_doctor").attr("disabled", "disabled");
				//				$(".Assigned_tothe_doctor").css("color", "#333333");
				//				$(".Assigned_tothe_doctor").css("border", "1px solid #333333");
				$.ajax({
					type: "post",
					url: serviceURL + "modification",
					async: true,
					data: {
						roomname: roomid,
						state: "待处理"
					},
					headers: {
						'Authorization': 'Bearer ' + msg.token
					},
					success: function(res) {
						console.log(res);
						$(".Assigned_tothe_doctor").text("待处理");
					},
					error: function(err) {
						layer.msg('发生错误,请重试！', {
							icon: 2
						});
					}
				});
			} else {
				layer.open({
					title: '系统提示',
					content: '指派医生失败!',
					success: function(layero) {
						 layero.find(".layui-layer-btn0").css({
						 	"border-color":"#1abb9c",
						 	"background-color":"#1abb9c"
						 })	
				    }
				});
			};
		},
		error: function(err) {
			layer.msg('发生错误,请重试！', {
				icon: 2
			});
		}
	})
})
//};

//函数外

// 文本发送
$('.Input_boxs').on('click', '.sends', (event) => {
	event.preventDefault();
	var username = $("#name").attr("data-username");
	var html = "";
	let text = $('.textarea_sends').val();
	if(text.length > 500) {
		layer.open({
			title: '系统提示',
			content: '发送消息内容超长,请分条发送',
			success: function(layero) {
						 layero.find(".layui-layer-btn0").css({
						 	"border-color":"#1abb9c",
						 	"background-color":"#1abb9c"
			})	
			}
		});
		return;
	};
	if(!text) {
		$('.Prompt_box').css({
			'display': 'block'
		})
		setTimeout(() => {
			$('.Prompt_box').css({
				'display': 'none'
			})
		}, 1500);
	} else {
		var time = new Date();
		console.log(text);
		html = `<li class="layim-chat-mine">
					<div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${$("#name").attr("data-username")}</i>${moment().format('hh:mm:ss')}</cite>
							</div>
							<div class="layim-chat-text" style="color:white;background-color=;background-color:#1abb9c;">${text}</div>
						</li>`
		$('.layim-chat-main>ul').append(html);
		$('.textarea_sends').val("");
		let pars = {
			msg: text,
			roomID: $(".username").attr("data-id"),
			username: $("#name").attr("data-username"),
			type: 'string',
			anonymityImg: "https://xcximg.juseyun.com/Images/servers.png",
			color: false,
			is: $("#name").attr("data-username"),
			b: 1,
			time: time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds()
		}
		socket.emit("message", {
			msg: text,
			roomID: $(".username").attr("data-id"),
			username: $("#name").attr("data-username"),
			userRole:$("#name").attr("userrole"),
			type: 'string',
			b: 1,
			anonymityImg: "https://xcximg.juseyun.com/Images/servers.png",
			color: false,
			headerimg: null,
			to: null,
			imggs: "",
			id: 0,
			is: $("#name").attr("data-username"),
			time: time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds()
		});
		//		chatrecord(pars);
		var div = document.getElementsByClassName('chat-thread')[0];
		div.scrollTop = div.scrollHeight;
	};
	//发送信息当前房间列表置前
	roomlist();
});
//保存聊天记录
function chatrecord(datas) {
	$.ajax({
		url: serviceURL + "chatrecord",
		type: "post",
		dataType: "json",
		data: datas,
		success: function(res) {
			console.log(res);
		},
		error: function(err) {
			console.log(err)
		}
	})
};
//发送信息房间列表置前
function roomlist() {
	let roomlist = $(".list-group").children("li");
	let roomid = $(".closes").attr("data-id");
	for(let a = 0; a < roomlist.length; a++) {
		if(roomlist[a].attributes.rooname.value == roomid) {
			//console.log(roomlist[a]);
			$(".list-group").prepend(roomlist[a]);
		}
	}
};

